# -*- coding: utf-8 -*-
"""Main Controller"""
import pylons
from pylons import response
from tg import expose, flash, require, url, request, redirect, config
from pylons.i18n import ugettext as _, lazy_ugettext as l_
from catwalk.tg2 import Catwalk
from repoze.what import predicates

from tgglobe.lib.base import BaseController
from tgglobe.model import DBSession, metadata
from tgglobe.controllers.error import ErrorController
from tgglobe import model
from tgglobe.controllers.secure import SecureController
from tgext.zeroisp.controllers.root import ToolboxController, CategoryController, PostController, TeamController, UserController, KeywordController
from tgext.zeroisp.controllers.json import JsonZeroisp
from tgext.zeroisp.widgets import *
from tgext.zeroisp.lib.helpers import GeoRSS
from tgglobe.lib import search_hotel
from tgext.zeroisp.lib.utils import get_locale
from tgext.zeroisp.controllers.default import DefaultController
from pylons.controllers.util import url_for

__all__ = ['RootController']

import logging

log = logging.getLogger(__name__)

class AdminController(BaseController):
    toolbox = ToolboxController('/admin/toolbox',
                                controllers_map=dict( category = CategoryController,
                                      post = PostController,
                                      team = TeamController,
                                      keyword = KeywordController,
                                      user = UserController,))

class RootController(BaseController, DefaultController):
    """
    The root controller for the tgglobe application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()

    #admin = Catwalk(model, DBSession)

    admin = AdminController()
    error = ErrorController()
    json  = JsonZeroisp(config.get('google.maps.key'))

    @expose('tgglobe.templates.index')
    @expose('json')
    def index(self, **kw):
        """Handle the front-page."""
        pylons.c.pack = pack
        action = "/show"
        pylons.c.googlemaps_js = self.googlemaps_js()
        pylons.c.address_form = LatLngForm(action=action)
        pylons.c.address_search_form = GmapSearchForm()
        pylons.c.gmap = Gmap(attrs=dict(style="min-width:300px; height:320px;"))

        return dict(page='index', root_url='/', value=kw, lang=get_locale())

    @expose('tgglobe.templates.show')
    @expose('json')
    def show(self, **kw):
        """Handle the front-page."""
        action = "/show"
        pylons.c.pack = pack
        pylons.c.googlemaps_js = self.googlemaps_js()
        google_lng = kw.get('google_lng')
        google_lat = kw.get('google_lat')
        hotels = []
        if google_lng and google_lat:
            hotels = search_hotel(float(google_lng), float(google_lat))
        return dict(page='index', root_url='/show', hotels=hotels, kw=kw)

    @expose()
    def feed(self, google_lat, google_lng):

        hotels = []
        if google_lng and google_lat:
            hotels = search_hotel(float(google_lng), float(google_lat))
        feed = GeoRSS(
            title=u"An excellent Sample Feed",
            link=url_for(),
            description=u"A sample feed, showing how to make and add entries",
            language=u"en",)
        center_lat = 0
        center_lng = 0
        index = 0
        for hotel in hotels:
            feed.add_item(title=hotel.name, link=hotel.hotel_url, description=hotel.html_description,
              google_lng=hotel.google_lng, google_lat=hotel.google_lat)
        response.content_type = 'application/rss+xml'
        return feed.writeString('utf-8')



    @expose('tgglobe.templates.login')
    def login(self, came_from=url('/')):
        """Start the user login."""
        login_counter = request.environ['repoze.who.logins']
        if login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login', login_counter=str(login_counter),
                    came_from=came_from)

    @expose()
    def post_login(self, came_from=url('/')):
        """
        Redirect the user to the initially requested page on successful
        authentication or redirect her back to the login page if login failed.

        """
        if not request.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect(url('/login', came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=url('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)
